<template>
    <div class="addressContainer">
        <el-form
            :model="form"
            :rules="formRules"
            ref="formRef"
            class="addForm"
            label-width="120px"
            v-loading="isLoading"
            element-loading-text="表单加载中..."
        >
            <el-form-item label="地址信息：" prop="region">
                <el-cascader
                    v-model="form.region"
                    :options="regions"
                    :props="props"
                    @clear="form.region = ''"
                    placeholder="请选择省市区"
                    filterable
                    clearable
                    ref="regionSelector"
                    style="width: 40rem"
                >
                    <template #default="{ node, data }">
                        <span>{{ data.name }}</span>
                    </template>
                </el-cascader>
            </el-form-item>
            <el-form-item label="邮政编码：" prop="code">
                <el-input v-model="form.code" placeholder="请输入邮政编码"></el-input>
            </el-form-item>
            <el-form-item label="详细地址：" prop="detail">
                <el-input
                    v-model="form.detail"
                    type="textarea"
                    resize="none"
                    rows="3"
                    placeholder="请输入详细地址 例：茶山街道景观大道1号温州理工学院"
                ></el-input>
            </el-form-item>
            <el-form-item label="收货人姓名：" prop="name">
                <el-input v-model="form.name" placeholder="请输入收货人姓名"></el-input>
            </el-form-item>
            <el-form-item label="手机号码：" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitAddress">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import service from "@/utils/request";
import axios from "axios";
import { ElMessage } from "element-plus";
import store from "@/store";

export default {
    name: "AddAddress",
    props: ["updateForm"],
    data() {
        return {
            regions: [],
            isLoading: true,
            isUpdate: false,
            // 级联选择器配置
            props: {
                value: "name",
                label: "name",
            },
            // 表单
            form: {
                region: null,
                code: "000000",
                detail: "",
                name: "",
                telephone: "",
            },
            // 表单验证
            formRules: {
                region: {
                    required: true,
                    type: "array",
                    validator: (rule, value, callback) => {
                        // console.log(value);
                        if (value === null || value === undefined) {
                            callback(new Error("地区不能为空"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "change",
                },
                detail: {
                    required: true,
                    validator: (rule, value, callback) => {
                        // console.log(value);
                        if (value === "") {
                            callback(new Error("详细地址不能为空"));
                        } else if (value.length < 5 || value.length > 100) {
                            callback(new Error("详细地址需在5-100个字符之间"));
                        } else {
                            callback();
                        }
                    },
                    min: 5,
                    max: 100,
                    trigger: "blur",
                },
                code: {
                    length: 6,
                    validator: (rule, value, callback) => {
                        if (!value.match(/[0-9]{6}/)) {
                            callback(new Error("邮政编码需为数字"));
                        } else if (value.length !== 6) {
                            callback(new Error("邮政编码需为6位"));
                        } else {
                            callback();
                        }
                    },
                },
                name: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("收货人姓名不能为空"));
                        } else if (value.length > 30) {
                            callback(new Error("收货人姓名不能长于30个字符"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "blur",
                    max: 30,
                },
                telephone: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请输入11位手机号"));
                        } else if (
                            !value.match(/^(13[0-9]|14[01456789]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/)
                        ) {
                            callback(new Error("手机号码格式不正确"));
                        } else {
                            callback();
                        }
                    },
                    length: 11,
                    trigger: "blur",
                },
            },
        };
    },
    methods: {
        submitAddress() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    if (this.isUpdate) {
                        this.form.region = this.form.region.join("");
                        console.log(this.form);
                        service({
                            method: "patch",
                            url: "/address/update",
                            headers: {
                                token: store.state.token,
                                "Content-type": "application/json",
                            },
                            data: {
                                ...this.form,
                            },
                        })
                            .then((res) => {
                                ElMessage({
                                    type: "success",
                                    message: "修改地址成功",
                                });
                                setTimeout(() => {
                                    this.$emit("close");
                                    window.location.reload();
                                }, 0);
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    } else {
                        this.form.region = this.form.region.join("");
                        // console.log(this.form);
                        service({
                            method: "post",
                            url: "/address/add",
                            headers: {
                                token: store.state.token,
                                "Content-type": "application/json",
                            },
                            data: {
                                userid: store.state.userInfo.userID,
                                status: 0,
                                ...this.form,
                            },
                        })
                            .then((res) => {
                                // console.log(res);
                                ElMessage({
                                    type: "success",
                                    message: "添加地址成功",
                                });
                                setTimeout(() => {
                                    window.location.reload();
                                }, 200);
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    }
                }
            });
        },
    },
    watch: {
        updateForm(oldVal) {
            this.form = oldVal;
        },
    },
    async beforeMount() {
        this.isLoading = true;
        await axios
            .get("https://www.wenjiangs.com/api/v2/xzqhSimple")
            .then((res) => {
                this.regions = res.data;
            })
            .catch((err) => {
                ElMessage({
                    type: "error",
                    message: "获取地区信息失败",
                });
            });
        if (this.updateForm) {
            this.form = this.updateForm;
            this.isUpdate = true;
        }
        this.isLoading = false;
    },
};
</script>

<style lang="scss" scoped>
.addressContainer {
    .addForm {
        width: 40rem;
    }
}
</style>
